package com.lykj.lib_base.net.http

import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.lykj.lib_base.app.BaseApplication
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody
import org.json.JSONObject


/**
 * ================================================
 * 自定义订阅者(ResponseBody).观察者
 * ================================================
 *
 * @author gosha
 * @date 2022/9/2-16:13
 */
abstract class CustomResponseBodyObserver<T : ResponseBody> : Observer<T> {
    private val TAG = "ResponseBodyObserver"
    abstract fun specificHandle(responseBody: String)
    abstract fun handleException(ret: String, msg: String?)

    override fun onSubscribe(d: Disposable) {
    }

    override fun onNext(t: T) {
//        val code: Int = t.c
//        if (code == 200) {
//        } else {
//            LogUtils.eTag(TAG, "$code:${t.message}")
//        }
        val responseBody = t.string()
        val jsonObject = JSONObject(responseBody)
        val ret = jsonObject.getString("code")
        val msg = jsonObject.getString("message")
        when (ret) {
            "200" -> {
                specificHandle(responseBody)
            }

            "410" -> {
                //token过期处理
                BaseApplication.instance?.clearUserInfo(onlyMemory = false)
                BaseApplication.instance?.clearAgentUserInfo(onlyMemory = false)
                LogUtils.e("410,重新登录")

                ActivityUtils.startActivity(
                    BaseApplication.instance!!.packageName,
                    "${BaseApplication.instance!!.packageName}.ui.activity.MobileLoginActivity"
                )
                //检测本地是否存在账户 1.存在 调用登录  2.不存在 调用其他登录
                //            if (GameExtManager.getInstance().hasLocalAccount()) {
                //                GameExtManager.getInstance().getActivity()
                //                    ?.let { ActivityUtils.finishToActivity(it, false) }
                //                ActivityUtils.startActivity(GELoginActivity::class.java)
                //            } else {
                //                GameExtManager.getInstance().getActivity()
                //                    ?.let { ActivityUtils.finishToActivity(it, false) }
                //                ActivityUtils.startActivity(GEOtherLoginActivity::class.java)
                //            }
            }

            else -> {
                //非常规业务返回错误处理
                handleException(ret, msg)
            }
        }
    }

    override fun onError(e: Throwable) {
        LogUtils.eTag(TAG, e.message)
    }

    override fun onComplete() {
    }
}